package com.yundasys.lab06ratelimitannotation.limit;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

/**
 * @PACKAGE_NAME: com.yundasys.lab06ratelimitannotation.limit
 * @NAME: AccessLimiter
 * @USER: jiangta
 * @DATE: 2021/1/21
 * @TIME: 9:00 下午
 * @PROJECT_NAME: springboot-labs
 */
@Service
@Slf4j
@Deprecated
public class AccessLimiter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    public void limitAccess(String key,Integer limit) {
        //step 1:request Lua script
        boolean acquired = stringRedisTemplate.execute(
                rateLimitLua,        //Lua script 的真身
                Lists.newArrayList(key), //Lua脚本中的key列表
                limit.toString()
        );

        if(!acquired) {
            log.error("Your access is blocked key={}", key);
            throw new RuntimeException("Your access is blocked");
        }
    }
}
